package baidu.reader.txt
{
    import baidu.reader.common.*;
    import baidu.reader.common.model.*;
    import baidu.reader.common.model.VO.*;
    import baidu.reader.txt.model.*;
    import baidu.reader.txt.ui.*;
    import baidu.ui.managers.*;

    import com.greensock.plugins.*;

    import flash.display.*;
    import flash.events.*;
    import flash.text.*;

    public class TxtReaderCore extends EventDispatcher implements IReaderCore
    {
        private var txtModel:TxtDataModel;
        private var tocModel:TocDataModel;
        private var chapModel:TxtChapterModel;
        private var configModel:AppConfigModel;
        private var preferenceModel:AppPreferenceModel;
        private var kbManager:KeyboardManager;
        private var stage:Stage;
        private var ui:TxtUIMain;

        public function TxtReaderCore()
        {
            return;
        }

        public function init(rStage:Stage) : void
        {
            this.stage = rStage;
            TweenPlugin.activate([AutoAlphaPlugin]);
            CursorManager.getInstance().root = rStage;
            TooltipManager.getInstance().root = rStage;
            this.initUI();
            this.initModel();
            this.initKeyboard();
            this.initJSCallBack();
            return;
        }

        private function initJSCallBack() : void
        {
            var jsManager:JSManager = InstanceManager.createSingletonInstance(JSManager);
            jsManager.addEventListener(ReaderEvent.HTML_MOUSE_WHEEL, this.mouseWheelHandler);
            return;
        }

        private function mouseWheelHandler(event:ReaderEvent) : void
        {
            var wheelEvent:MouseEvent = new MouseEvent(MouseEvent.MOUSE_WHEEL);
			wheelEvent.delta = int(event.data);
            this.stage.dispatchEvent(wheelEvent);
            return;
        }

        private function initKeyboard() : void
        {
            this.kbManager = InstanceManager.createSingletonInstance(KeyboardManager);
            this.kbManager.initListeners();
            this.kbManager.addEventListener(ReaderEvent.GO_NEXT_PAGE, this.goNextPageHandler);
            this.kbManager.addEventListener(ReaderEvent.GO_PREV_PAGE, this.goPrevPageHandler);
            this.kbManager.addEventListener(ReaderEvent.GO_NEXT_LINE, this.goNextLineHandler);
            this.kbManager.addEventListener(ReaderEvent.GO_PREV_LINE, this.goPrevLineHandler);
            return;
        }

        private function initUI() : void
        {
            this.stage.showDefaultContextMenu = false;
            this.stage.scaleMode = StageScaleMode.NO_SCALE;
            this.stage.align = StageAlign.TOP_LEFT;
            this.ui = new TxtUIMain();
            this.ui.addEventListener(ReaderEvent.GO_NEXT_PAGE, this.goNextPageHandler);
            this.ui.addEventListener(ReaderEvent.GO_PREV_PAGE, this.goPrevPageHandler);
            this.ui.addEventListener(ReaderEvent.GO_NEXT_CHAPTER, this.goNextChapHandler);
            this.ui.addEventListener(ReaderEvent.SHOW_TOC, this.doShowTocPage);
            this.ui.addEventListener(ReaderEvent.GO_BACK_FROM_TOC, this.doHideTocPage);
            this.ui.addEventListener(ReaderEvent.GO_FIRST_PAGE, this.doGoFirstPage);
            this.ui.addEventListener(ReaderEvent.TOC_GO_TO_PAGE, this.doGotoBookmark);
            this.ui.addEventListener(ReaderEvent.TOGGLE_FULLSCREEN, this.toggleFullscreenHandler);
            this.ui.addEventListener(ReaderEvent.SHOW_SETTING_PANEL, this.showSettingHandler);
            this.ui.addEventListener(ReaderEvent.CLOSE_SETTING_PANEL, this.closeSettingHandler);
            this.ui.addEventListener(ReaderEvent.TEXT_FORMAT_CHANGED, this.textFormatChangeHandler);
            this.ui.addEventListener(ReaderEvent.GO_SINGLE_PAGE, this.goSingleHandler);
            this.ui.addEventListener(ReaderEvent.GO_DOUBLE_PAGE, this.goDoubleHandler);
            this.ui.addEventListener(ReaderEvent.GO_TO_POSITION, this.goToPositionHandler);
            this.ui.addEventListener(ReaderEvent.SCROLL, this.pageChangeHandler);
            this.ui.addEventListener(ReaderEvent.SCROLLED_BOTTOM, this.textScrolledBottomHandler);
            this.ui.addEventListener(ReaderEvent.SCROLLED_TOP, this.textScrolledTopHandler);
            this.stage.addChild(this.ui);
            this.refreshUI();
            return;
        }

        private function goToPositionHandler(event:ReaderEvent) : void
        {
            var _loc_3:String = null;
            var _loc_4:TocItemVO = null;
            var _loc_2:* = event.data.pn;
            if (!event.data.docid)
            {
                if (_loc_2 > this.configModel.serialTotalPage || _loc_2 <= 0)
                {
                    return;
                }
                _loc_4 = this.configModel.getPositionBySerialPage(_loc_2);
                _loc_3 = _loc_4.docid;
                _loc_2 = _loc_4.page;
            }
            else
            {
                _loc_3 = event.data.docid;
            }
            this.chapModel.gotoTextPosition(_loc_3, _loc_2, 0);
            return;
        }

        private function textFormatChangeHandler(event:ReaderEvent) : void
        {
            this.ui.pageViewport.setTextFormat(event.data as TextFormat);
            return;
        }

        private function closeSettingHandler(event:ReaderEvent) : void
        {
            this.ui.closeSettingPanel();
            return;
        }

        private function showSettingHandler(event:ReaderEvent) : void
        {
            this.ui.showSettingPanel();
            return;
        }

        private function doGoFirstPage(event:ReaderEvent) : void
        {
            this.ui.showPageContent();
            this.chapModel.gotoChapter(0);
            return;
        }

        private function goPrevPageHandler(event:ReaderEvent) : void
        {
            if (!this.chapModel.isBusy && (this.ui.pageViewport.scrollPercent <= 0 || isNaN(this.ui.pageViewport.scrollPercent)))
            {
                if (!this.chapModel.gotoPreviousChapter())
                {
                    return;
                }
                if (this.ui.pageViewport is TxtSingleBookPage)
                {
                    (this.ui.pageViewport as TxtSingleBookPage).updatePending = true;
                }
            }
            this.ui.pageViewport.goPreviousPage();
            return;
        }

        private function goNextPageHandler(event:ReaderEvent) : void
        {
            if (!this.chapModel.isBusy && (this.ui.pageViewport.scrollPercent >= 100 || isNaN(this.ui.pageViewport.scrollPercent)))
            {
                if (!this.chapModel.gotoNextChapter())
                {
                    return;
                }
            }
            this.ui.pageViewport.goNextPage();
            return;
        }

        private function goNextChapHandler(event:ReaderEvent) : void
        {
            if (!this.chapModel.gotoNextChapter())
            {
                return;
            }
            this.ui.pageViewport.goNextPage();
            return;
        }

        private function goPrevLineHandler(event:ReaderEvent) : void
        {
            if (!this.chapModel.isBusy && this.ui.pageViewport.scrollPercent <= 0 && this.preferenceModel.displayType != AppPreferenceVO.DOUBLE_PAGE)
            {
                this.chapModel.gotoPreviousChapter();
            }
            this.ui.pageViewport.goUp();
            return;
        }

        private function goNextLineHandler(event:ReaderEvent) : void
        {
            if (!this.chapModel.isBusy && this.ui.pageViewport.scrollPercent >= 100 && this.preferenceModel.displayType != AppPreferenceVO.DOUBLE_PAGE)
            {
                this.chapModel.gotoNextChapter();
            }
            this.ui.pageViewport.goDown();
            return;
        }

        private function toggleFullscreenHandler(event:ReaderEvent) : void
        {
            this.stage.displayState = this.stage.displayState == StageDisplayState.NORMAL ? (StageDisplayState.FULL_SCREEN) : (StageDisplayState.NORMAL);
            this.ui.closeSettingPanel();
            return;
        }

        private function textScrolledTopHandler(event:ReaderEvent) : void
        {
            this.chapModel.loadChapterContentPrevious();
            return;
        }

        private function textScrolledBottomHandler(event:ReaderEvent) : void
        {
            this.chapModel.loadChapterContentNext();
            return;
        }

        private function pageChangeHandler(event:ReaderEvent) : void
        {
            var _loc_2:int = 0;
            var _loc_4:Array = null;
            var _loc_10:int = 0;
            var _loc_11:int = 0;
            var _loc_3:* = this.ui.pageViewport.getSecondLineFirstCharIndex();
            if (_loc_3 == -1)
            {
                return;
            }
            var _loc_5:* = this.chapModel.blockDelimiterArray;
            var _loc_6:* = this.txtModel.pageStartArrays;
            var _loc_7:int = 0;
            while (_loc_7 < (_loc_5.length - 1))
            {

                if (_loc_3 < _loc_5[(_loc_7 + 1)])
                {
                    _loc_4 = _loc_6[_loc_7 + this.txtModel.blockCacheStart];
                    break;
                }
                _loc_7++;
            }
            if (!_loc_4)
            {
                _loc_7 = _loc_5.length - 1;
                _loc_4 = _loc_6[_loc_7 + this.txtModel.blockCacheStart];
            }
            if (!_loc_4)
            {
                return;
            }
            var _loc_8:* = this.chapModel.chapterStartInBlockArray;
            _loc_3 = _loc_3 + this.chapModel.chapterStartInBlockArray[_loc_7] - _loc_5[_loc_7];
            var _loc_9:int = 0;
            _loc_10 = _loc_4.length;
            _loc_11 = 0;
            while (_loc_11 < (_loc_10 - 1))
            {

                if (_loc_3 < _loc_4[(_loc_11 + 1)])
                {
                    _loc_2 = _loc_11;
                    _loc_9 = _loc_3 - _loc_4[_loc_11];
                    break;
                }
                _loc_11++;
            }
            _loc_2 = _loc_2 + (_loc_7 + this.txtModel.blockCacheStart) * this.txtModel.default_rn;
            var _loc_12:* = _loc_2 + this.configModel.getFirstPage(this.txtModel.currentDocid);
            if (_loc_2 + this.configModel.getFirstPage(this.txtModel.currentDocid) == (this.configModel.serialTotalPage - 1) && event.data == 1)
            {
                _loc_2 = _loc_2 + 1;
            }
            this.ui.setPageNumber(_loc_2 + this.configModel.getFirstPage(this.txtModel.currentDocid), this.configModel.serialTotalPage);
            var _loc_13:* = _loc_2 + this.configModel.getFirstPage(this.txtModel.currentDocid);
            trace(this.ui.pageViewport.scrollPercent);
            if (_loc_13 <= 1 && (this.ui.pageViewport.scrollPercent <= 0 || isNaN(this.ui.pageViewport.scrollPercent)) && this.chapModel.currentChapterIndex == 0)
            {
                this.ui.pageViewport.canGoNext = true;
                this.ui.pageViewport.canGoPrevious = false;
            }
            else if (_loc_13 >= this.configModel.serialTotalPage && (this.ui.pageViewport.scrollPercent >= 100 || isNaN(this.ui.pageViewport.scrollPercent)))
            {
                this.ui.pageViewport.canGoNext = false;
                this.ui.pageViewport.canGoPrevious = true;
            }
            else
            {
                this.ui.pageViewport.canGoNext = true;
                this.ui.pageViewport.canGoPrevious = true;
            }
            _loc_9 = 0;
            _loc_3 = this.ui.pageViewport.getCurrentFirstCharIndex();
            _loc_10 = _loc_4.length;
            _loc_11 = 0;
            while (_loc_11 < (_loc_10 - 1))
            {

                if (_loc_3 < _loc_4[(_loc_11 + 1)])
                {
                    _loc_9 = _loc_3 - _loc_4[_loc_11];
                    break;
                }
                _loc_11++;
            }
            var _loc_14:* = new BookmarkItemVO(this.configModel.serialid, this.txtModel.currentDocid, _loc_2, _loc_9);
            LocalStorageModel.setLastPosition(_loc_14);
            return;
        }

        private function displayTypeChangeHandler(event:ReaderEvent) : void
        {
            return;
        }

        private function doGotoBookmark(event:ReaderEvent) : void
        {
            var _loc_2:* = event.target.value;
            this.ui.showPageContent();
            this.chapModel.gotoChapter(_loc_2);
            return;
        }

        private function doHideTocPage(event:ReaderEvent) : void
        {
            this.ui.showPageContent();
            return;
        }

        private function doShowTocPage(event:ReaderEvent) : void
        {
            this.ui.showToC();
            return;
        }

        private function stageResizeHandler(event:Event) : void
        {
            this.refreshUI();
            return;
        }

        private function refreshUI() : void
        {
            if (!this.ui)
            {
                return;
            }
            this.ui.x = 0;
            this.ui.y = 0;
            this.ui.width = this.stage.stageWidth;
            this.ui.height = this.stage.stageHeight;
            return;
        }

        private function initModel() : void
        {
            var screenModel:ScreenModel = InstanceManager.createSingletonInstance(ScreenModel);
			screenModel.addEventListener(Event.RESIZE, this.stageResizeHandler);
            this.configModel = InstanceManager.createSingletonInstance(AppConfigModel);
            this.tocModel = InstanceManager.createSingletonInstance(TocDataModel);
            this.tocModel.getTocData();
            this.tocModel.addEventListener(Event.CHANGE, this.tocLoadHandler);
            this.txtModel = InstanceManager.createSingletonInstance(TxtDataModel);
            this.txtModel.addEventListener(Event.CHANGE, this.contentChangeHandler);
            this.chapModel = InstanceManager.createSingletonInstance(TxtChapterModel);
            this.preferenceModel = InstanceManager.createSingletonInstance(AppPreferenceModel);
            this.preferenceModel.addEventListener(ReaderEvent.DISPLAY_TYPE_CHANGED, this.displayTypeChangeHandler);
            return;
        }

        private function tocLoadHandler(event:Event) : void
        {
            this.initApp();
            return;
        }

        private function initApp() : void
        {
            var _loc_2:TocItemVO = null;
            if (this.configModel.goLatestChpater)
            {
                this.ui.showPageContent();
                _loc_2 = this.tocModel.tocData[(this.tocModel.tocData.length - 1)];
                this.chapModel.gotoTextPosition(_loc_2.docid, _loc_2.page, _loc_2.offset);
                return;
            }
            var _loc_1:* = LocalStorageModel.getCurrentSerialIDLastPosition(this.configModel.serialid);
            if (!_loc_1)
            {
                this.ui.showToC(true);
                this.ui.showEnterButton();
            }
            else
            {
                this.ui.showPageContent();
                this.chapModel.gotoTextPosition(_loc_1.docid, _loc_1.pn, _loc_1.offset);
            }
            return;
        }

        private function contentChangeHandler(event:Event) : void
        {
            this.ui.setPageNumber(NaN, this.txtModel.totalPage);
            return;
        }

        private function goSingleHandler(event:ReaderEvent) : void
        {
            var _loc_2:BookmarkItemVO = null;
            if (!this.preferenceModel)
            {
                return;
            }
            this.preferenceModel.displayType = AppPreferenceVO.SINGLE_PAGE;
            if (!this.chapModel.isBusy && this.chapModel.currentChapterIndex != -1)
            {
                this.chapModel.dispatchEvent(new Event(Event.COMPLETE));
                _loc_2 = LocalStorageModel.getCurrentSerialIDLastPosition(this.configModel.serialid);
                this.chapModel.gotoTextPosition(_loc_2.docid, _loc_2.pn, _loc_2.offset);
            }
            return;
        }

        private function goDoubleHandler(event:ReaderEvent) : void
        {
            var _loc_2:BookmarkItemVO = null;
            this.preferenceModel.displayType = AppPreferenceVO.DOUBLE_PAGE;
            if (!this.chapModel.isBusy && this.chapModel.currentChapterIndex != -1)
            {
                this.chapModel.dispatchEvent(new Event(Event.COMPLETE));
                _loc_2 = LocalStorageModel.getCurrentSerialIDLastPosition(this.configModel.serialid);
                this.chapModel.gotoTextPosition(_loc_2.docid, _loc_2.pn, _loc_2.offset);
            }
            return;
        }

    }
}
